import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import store from "../index";

const user = {
  state: {
    token: getToken(),
    name: '',
    avatar: '',
    userId: null,
    roles: [],
    permissions: []
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
      localStorage.setItem('token', token)
      setToken(token)
    },
    SET_NAME: (state, name) => {
      localStorage.setItem('name', name)
      state.name = name
    },
    SET_USERID: (state, userId) => {
      localStorage.setItem('userId', userId)
      state.userId = userId
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo).then(res => {
            console.log(res,'登录');
          setToken(res.data.token)
          commit('SET_TOKEN', res.data.token)
          commit('SET_NAME', res.data.phoneNumber)
          commit('SET_USERID', res.data.userId)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        if (localStorage.getItem('token')) {
          commit('SET_ROLES', ['admin'])
          commit('SET_PERMISSIONS', ['*:*:*'])
          commit('SET_AVATAR', 'avatar')
          resolve()
        } else {
          reject()
        }
      })
    },

    // 退出系统
    LogOut({ commit, state }) {
      removeToken()
      // return new Promise((resolve, reject) => {
      //   logout(state.token).then(() => {
      //     commit('SET_TOKEN', '')
      //     commit('SET_ROLES', [])
      //     commit('SET_PERMISSIONS', [])
      //     removeToken()
      //     resolve()
      //   }).catch(error => {
      //     reject(error)
      //   })
      // })
    },
  }
}

export default user
